//
//  NetworkTools.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/20.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}

private let WBERRORDOMAIN = "cn.yangperlove.error"

class NetworkTools: AFHTTPSessionManager {
    //swift单例对象
    static let shareTools: NetworkTools = {
//        let baseString = "https://api.weibo.com/"
//        let baseUrl = NSURL(string: baseString)
        let share = NetworkTools()
        share.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return share
    }()
    
    func networkRequest(httpMehtod: HTTPMethod, urlString: String, parameters: [String : String]?, finished: (dict: [String:AnyObject]?, error: NSError?) -> ()) {
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
        if httpMehtod == .POST {
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
    
                guard let dict = result as? [String : AnyObject] else {
                    print("数据格式不合法")
                    //执行失败的回调
                    //domain: 域
                    //code: 自定义error 使用负数
                    let myError = NSError(domain: WBERRORDOMAIN, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据格式不合法"])
                    finished(dict: nil, error: myError)
                    return
                }

                finished(dict: dict, error: nil)
                }) { (_, error) -> Void in
                    print("error",error)
                    finished(dict: nil, error: error)
                    
            }
        } else if httpMehtod == .GET{
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                let dict = result as! [String:AnyObject]
                finished(dict: dict, error: nil)
                }) { (_, error) -> Void in
                    print("error",error)
                    finished(dict: nil, error: error)
            }

        }
        
        
        
    }

}